package com.wsz.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wsz.security.config.filter.LoginFilter;
import com.wsz.security.config.handler.LoginHandler;
import com.wsz.security.service.impl.UserDetailsServerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServerImpl userDetailsServer;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServer);
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setFilterProcessesUrl("/doLogin");
        loginFilter.setCode("code");
        loginFilter.setUsernameParameter("username");
        loginFilter.setPasswordParameter("password");
        loginFilter.setAuthenticationManager(authenticationManager());
        loginFilter.setAuthenticationSuccessHandler(new LoginHandler());
        loginFilter.setAuthenticationFailureHandler(new LoginHandler());
        return loginFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("vc.jpg").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((req,resp,ex)->{
                    resp.setContentType("application/json;charset=UTF-8");
                    resp.setStatus(501);
                    resp.getWriter().println("必须认证后才能访问");
                })
                .and()
                .logout()
                .and()
                .csrf().disable()
                .sessionManagement()
                .maximumSessions(1)
                .expiredSessionStrategy((event)->{
                    HttpServletResponse response = event.getResponse();
                    response.setContentType("application/json;charset=UTF-8");
                    Map<String,Object> data = new HashMap<>();
                    data.put("msg:","该账户已在其他地点登录");
                    data.put("status:",201);
                    String s = new ObjectMapper().writeValueAsString(data);
                    response.getWriter().println(s);
                    response.flushBuffer();
                });


        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
